<template>
	<view class="container">
	<view class="teacherlayout">
		<view class="teacher-info">
		    <!-- 用户有头像就用用户的头像，没有就默认的avatar -->
			<view class="avatar-image">
				<image class="avatar" :src="imagePath" mode="aspectFill"></image>
			</view>
		    <!-- 右侧用户信息 -->
			<view class="user-info">
				<view class="username">{{userInfo.name}}</view>
				<view class="slogan">教师ID: {{userInfo.teacherId}}</view>
			</view>
			
		</view>
		<view class="classandtimetable">
			<view class="class-create" @click="openpopup">
				<text class="cuIcon cuIcon-roundadd"></text>
				<view>创建班级</view>
			</view>
			<view class="timeable-input" @click="gototimeable">
				<text class="cuIcon cuIcon-read"></text>
				<view> 课程表 </view>
			</view>
		</view>
		<popup :show="show" @close="closepopup" @confirm="createclasses" title="创建班级">
			<input 
			class="class-input" 
			type="text" 
			placeholder="请输入班级名称" 
			v-model="classname"
			/>
		</popup>
		<view class="class-info">
			<view class="class-detail" v-for="(item,index) in classlist" :key='item.id' @click="gotoclassdetail(item)">
				<text>{{item.class_name}}</text>
			<view class="class-meta">
			  <text>班主任: {{item.teacher_name || '未分配'}}</text>
			<text>人数: {{item.students || 0}}</text>
			</view>
			</view>
		</view>
		
		<view class="tab-bar">
		      <view 
		        class="tab-item" 
		        :class="{active: currentTab === 0}" 
		        @click="switchTab(0)"
		      >
		        <text class="cuIcon cuIcon-home"></text>
		        <text class="tab-text">首页</text>
		      </view>
		      <view 
		        class="tab-item" 
		        :class="{active: currentTab === 1}" 
		        @click="switchTab(1)"
		      >
		        <text class="cuIcon cuIcon-form"></text>
		        <text class="tab-text">申请</text>
		      </view>
		      <view 
		        class="tab-item" 
		        :class="{active: currentTab === 2}" 
		        @click="switchTab(2)"
		      >
		        <text class="cuIcon cuIcon-message"></text>
		        <text class="tab-text">消息</text>
		      </view>
		      <view 
		        class="tab-item" 
		        :class="{active: currentTab === 3}" 
		        @click="switchTab(3)"
		      >
		        <text class="cuIcon cuIcon-my"></text>
		        <text class="tab-text">我的</text>
		      </view>
		    </view>
		  </view>
		  </view>
		</template>

<script>
	import popup from '../../components/popup/popup.vue'
	import wButton from '../../components/watch-login/watch-button.vue'
	
	export default {
		data() {
			return {
				show:false,
				currentTab: 0,
				classname:'',
				classlist:uni.getStorageSync('classlist')||[],
				userInfo: {} ,// 新增用户信息数据,
				imagePath: uni.getStorageSync('teacherAvatar')  || require('@/static/images/avatar.png'),
				mockTeachers: {
				      '2023111111111': {
				        id: '2023111111111',
				        teacher_name: "李老师",
				        gender: 1,
				        address: "厚德楼B801",
				        phone_number: 18000000000,
				        age: 35,
				        blood: "B",
				        status: 1,
						students:30,
				      }
				    },
			};
		},
		components:{popup, wButton},
		onShow() {
			this.checkLoginStatus();
			this.currentTab = 0
			    uni.$emit('updateTab', 0) // 如果需要跨页面同步
		},
		methods:{
			// 检查登录状态
			checkLoginStatus() {
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.redirectTo({ url: '/pages/login/login' })
					return
				}
				// this.userInfo = {
				// 	name: userInfo.name,
				// 	teacherId: userInfo.teacherId || userInfo.staffId // 根据实际字段调整
					this.userInfo = {
				    name: userInfo.name,
				    teacherId: userInfo.id || '2023111111111', // 使用模拟数据中的ID
				    role: userInfo.roleName // 新增角色信息
				}
			},
			switchTab(index) {
			      const routes = [
			        '/pages/teacher/teacher',
			        '/pages/application/list',
			        '/pages/notification/list',
			        '/pages/user/profile'
			      ];
			      if (index >= routes.length) {
			        uni.showToast({
			          title: '功能正在开发中',
			          icon: 'none'
			        });
			        return;
			      }
			      uni.navigateTo({ 
			            url: routes[index],
			            success: () => {
			              console.log('路由跳转成功:', routes[index]);
			            },
			            fail: (err) => {
			              console.error('路由跳转失败:', err);
			              uni.showToast({
			                title: '页面加载失败',
			                icon: 'none'
			              });
			            }
			          });
			},
		
			
			// //模拟班级的创建（基于数据库）
			// mockcreateclass(teacherId, className) {
			//   return new Promise((resolve, reject) => {
			//     setTimeout(() => {
			//       // 1. 参数检查
			//       if (!teacherId) {
			//         reject({ code: 400, message: "缺少教师ID参数" });
			//         return;
			//       }
			      
			//       // 2. 检查教师是否存在（模拟数据库查询）
			//       const mockTeachers = {
			//         "T2023111111111": {
			//           id: "2023111111111",
			//           teacher_name: "张三",
			//           gender: 1,
			//           address: "厚德楼B801",
			//           phone_number: 18029989462,
			//           age: 32,
			//           blood: "B",
			//           status: 1
			//         }
			//       };
			      
			//       const teacher = mockTeachers[teacherId];
			//       if (!teacher) {
			//         reject({ code: 404, message: "该教师不存在" });
			//         return;
			//       }
			      
			//       // 3. 检查是否已有同名班级（从本地存储中检查）
			//       const existingClasses = uni.getStorageSync('classlist') || [];
			//       if (existingClasses.some(cls => cls.class_name === className)) {
			//         reject({ code: 409, message: "已存在同名班级" });
			//         return;
			//       }
			      
			//       // 4. 创建班级
			//       const newClassId = 51992117;
			      
			//       const newClass = {
			//         id: newClassId,
			//         class_name: className,
			//         teacher_id: teacher.id,
			//         teacher_name: teacher.teacher_name
			//       };
			      
			//       resolve({
			//         code: 200,
			//         message: "创建班级成功",
			//         data: newClass
			//       });
			//     }, 700);
			//   });
			// },
			async mockcreateclass(teacherId, className) {
			      // 模拟网络延迟
			      await new Promise(resolve => setTimeout(resolve, 500))
			      
			      // 检查教师是否存在
			      const teacher = this.mockTeachers[teacherId]
			      if (!teacher) {
			        throw new Error('教师信息不存在')
			      }
			
			      // 检查重复班级名
			      const exists = this.classlist.some(c => c.class_name === className)
			      if (exists) {
			        throw new Error('班级名称已存在')
			      }
			
			      // 生成模拟班级数据
			      const newClass = {
			          id: Date.now().toString(),
			          class_name: className,
			          teacher_id: teacherId,
			          teacher_name: teacher.teacher_name || '未分配',
			          students: 0  // 初始人数设为0
			      }
			
			      return {
			        code: 200,
			        message: '班级创建成功',
			        data: newClass
			      }
			    },
			openpopup(){
				this.show=true
			},
			closepopup(){
				this.show=false
				this.classname=''
			},
			
			// 点击跳转到课程表
			gototimeable(){
				uni.navigateTo({
					url: '/pages/timeable/timeable'
				})
			},
			
			//点击跳转到班级详情页
			gotoclassdetail(item) {
			  uni.navigateTo({
			    url: `/pages/classdetail/classdetail?classitem=${JSON.stringify(item)}`
			  })
			},
					
			//创建班级
			// async createclasses(){
			// 	this.show=false
			// 	if (!this.classname || this.classname.trim() === ''){
			// 		return uni.showToast({
			// 			title:'班级名不能为空',
			// 			icon: 'none',
			// 			duration: 1000
			// 		})
			// 	}
			// 	uni.showLoading({ title:'班级创建中....'})
			// 	try{
			// 		const res=await this.mockcreateclass(this.userInfo.teacherId,this.classname)
			// 		if(res.code===200){
			// 			uni.showToast({
			// 				title:res.message||'创建班级成功',
			// 				icon:'success',
			// 				duration:2000
			// 			})
			// 		}
			// 		this.classlist=[res.data,...this.classlist]
			// 		uni.setStorageSync('classlist',this.classlist)
			// 		console.log(this.classlist)
			// 		this.classname=''
			// 	}catch(error){
			// 		uni.showToast({
			// 			title:error.message||'创建班级失败',
			// 			icon:'none',
			// 			duration:2000
			// 		})
			// 	}finally{
			// 		uni.hideLoading();
			async createclasses() {
			      this.show = false
			      if (!this.classname.trim()) {
			        uni.showToast({ title: '班级名不能为空', icon: 'none' })
			        return
			      }
			
			      uni.showLoading({ title: '创建中...' })
			      
			      try {
			        // 使用模拟教师ID
			        const teacherId = this.userInfo.teacherId
			        const res = await this.mockcreateclass(teacherId, this.classname)
			        
			        // 更新本地数据
			        this.classlist = [res.data, ...this.classlist]
			        uni.setStorageSync('classlist', this.classlist)
			        
			        uni.showToast({
			          title: res.message,
			          icon: 'success'
			        })
			      } catch (error) {
			        uni.showToast({
			          title: error.message,
			          icon: 'none'
			        })
			      } finally {
			        uni.hideLoading()
			        this.classname = ''
				}
			}
		}
	}
</script>

<style>
	@import url("css/teacher.css");
	@import url("../../components/watch-login/css/icon.css");
</style>